import { RootState } from '@/types/store';
import Vue from 'vue';
import Vuex, { Store } from 'vuex';
import auth from './auth';
import address from './address';
import community from './community';
import crowd from './crowd';
import feedback from './feedback';
import framework from './framework';
import good from './good';
import manage from './manage';
import order from './order';
import partner from './partner';
import pkg from './pkg';
import product from './product';
import shop from './shop';
import user from './user';
import utils from './utils';
import clonedeep from 'lodash.clonedeep';

Vue.use(Vuex);

window.addEventListener('wxunload', () => {
    // 每次页面销毁
    window.setTimeout(() => {
        // @ts-ignore
        window.$$publish('refresh_store');
    });
});

// @ts-ignore
window.$$subscribe('refresh_store', () => {
    // @ts-ignore
    store.replaceState(clonedeep(window.$$global.state));
});

const mpMultiPage = (store: Store<RootState>) => {
    store.subscribe((mutation, state) => {
        // 更新数据
        // @ts-ignore
        window.$$global.state = store.state;
    });
}

const store = new Vuex.Store<RootState>({
    modules: {
        auth,
        address,
        community,
        crowd,
        feedback,
        framework,
        good,
        manage,
        order,
        partner,
        pkg,
        product,
        shop,
        user,
        utils,
    },
    plugins: [
        mpMultiPage,
    ],
});

// @ts-ignore
if (window.$$global.state) {
    // @ts-ignore
    store.replaceState(clonedeep(window.$$global.state));
}

export default store;
